package com.pan.crawler.impl6;

import com.pan.crawler.Page;
import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.edge.EdgeDriver;

import java.time.Duration;

public class PageImpl6 implements Page {

    private EdgeDriver edgeDriver;

    public PageImpl6(){
        edgeDriver = new EdgeDriver();
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        edgeDriver.manage().window().minimize();
    }
    @Override
    public String get(Chapter chapter) {
        String content = chapter.getTitle()+"\n\n\n\n\n\n\n";
        for (int i = 0; i < 5; i++) {
            try {
                edgeDriver.navigate().to(chapter.getUrl());
                edgeDriver.findElement(By.className("copyright"));
                content += edgeDriver.findElement(By.id("BookText")).getText();
                break;
            }catch (Exception e){
                if (i==4){
                    throw new RuntimeException("多次爬取章节失败，中断爬取");
                }
                if (edgeDriver.findElement(By.cssSelector("title")).getText().equals("403 Forbidden")){
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
        content+="\n\n\n\n\n\n\n\n";
        return content;
    }

    @Override
    public void close() {
        edgeDriver.quit();
    }
}
